package com.thd.kotlinapp.service

import android.app.Dialog
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.thd.kotlinapp.constant.Constants
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Calendar

class SchedulerService : Service() {

    private val tag : String = "SchedulerService"
    //协程作用域
    private val serviceJob = Job()


    private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)

    override fun onCreate() {
        startSchedulerTask()
        super.onCreate()
    }

    override fun onBind(p0: Intent?): IBinder? {
        TODO("Not yet implemented")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    private fun startSchedulerTask(){
        serviceScope.launch {
            while (true){
                var nowHour : Int = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
                var nowMinute : Int = Calendar.getInstance().get(Calendar.MINUTE)
                Log.d(tag,"当前时间:" + nowHour + ":" + nowMinute)
                if (Constants.schedulerTask != null){
                    //存在定时任务
                    val schedulerTime : Array<String> = Constants.schedulerTask!!.split(":").toTypedArray()
                    var schedulerHour : Int = Integer.parseInt(schedulerTime[0])
                    var schedulerMinute : Int = Integer.parseInt(schedulerTime[1])
                    Log.d(tag,"定时时间为:" + Constants.schedulerTask)
                    if (nowHour == schedulerHour && nowMinute == schedulerMinute){
                        Log.d(tag,"到达时间:" + Constants.schedulerTask + " 内容:" + Constants.schedulerContain)
                        Handler(Looper.getMainLooper()).post{
                            Log.d(tag,"切换主线程");
                            Toast.makeText(applicationContext,Constants.schedulerContain,Toast.LENGTH_SHORT).show()
                        }
                    }

                }
                delay(60000)
            }
        }
    }


}